<!-- src/pages/index/ReportIssue/ReportIssue.vue -->
<template>
  <view class="report-page">
    <scroll-view scroll-y class="content">
      <view class="form-container">
        <view class="section">
          <view class="section-title">古树信息</view>
          <view class="tree-info">
            <text class="tree-name">{{ treeInfo.chineseName }} {{ treeInfo.scientificName }}</text>
            <text class="tree-location">{{ treeInfo.provinceName }}{{ treeInfo.cityName }}{{ treeInfo.districtName
            }}</text>
          </view>
        </view>

        <view class="section">
          <view class="section-title">异常信息</view>

          <view class="form-item">
            <text class="label">异常类型 *</text>
            <picker mode="selector" :range="issueTypes" @change="onIssueTypeChange" :value="selectedIssueTypeIndex">
              <view class="picker">
                <text :class="{ placeholder: selectedIssueTypeIndex === -1 }">
                  {{ selectedIssueTypeIndex === -1 ? '请选择异常类型' : issueTypes[selectedIssueTypeIndex] }}
                </text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">详细描述 *</text>
            <textarea placeholder="请详细描述您发现的问题..." v-model="reportContent" maxlength="500" class="textarea" />
            <view class="char-count">{{ reportContent.length }}/500</view>
          </view>
        </view>

        <view class="section">
          <view class="section-title">异常图片</view>
          <view class="image-upload-section">
            <view class="image-grid">
              <view class="image-item" v-for="(image, index) in uploadedImages" :key="index">
                <image :src="image" mode="aspectFill" class="uploaded-image" />
                <text class="remove-btn" @tap="removeImage(index)">×</text>
              </view>
              <view class="upload-btn" v-if="uploadedImages.length < 4" @tap="chooseImage">
                <text class="upload-icon">+</text>
                <text class="upload-text">上传图片</text>
              </view>
            </view>
            <view class="upload-hint">最多可上传4张图片，支持JPG、PNG格式</view>
          </view>
        </view>

        <view class="section">
          <view class="section-title">联系方式（可选）</view>
          <view class="form-item">
            <input type="text" placeholder="便于我们联系您确认问题" v-model="contactInfo" class="input" />
          </view>
        </view>
      </view>
    </scroll-view>

    <view class="footer">
      <button class="submit-btn" @tap="submitReport" :disabled="isSubmitting">
        {{ isSubmitting ? '提交中...' : '提交报告' }}
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { postIssueTreeAPI } from '@/services/tree'

// 页面数据
const treeInfo = ref({})
const issueTypes = ['位置信息错误', '树木状态变化', '基本信息错误', '图片问题', '其他问题']
const selectedIssueTypeIndex = ref(-1)
const reportContent = ref('')
const contactInfo = ref('')
const uploadedImages = ref([])
const isSubmitting = ref(false)

// 获取传递的参数
onLoad((options) => {
  if (options.treeInfo) {
    treeInfo.value = JSON.parse(decodeURIComponent(options.treeInfo))
  }
})

// 选择异常类型
const onIssueTypeChange = (e) => {
  selectedIssueTypeIndex.value = e.detail.value
}

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 4 - uploadedImages.value.length,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      uploadedImages.value = [...uploadedImages.value, ...res.tempFilePaths]
    }
  })
}

// 移除图片
const removeImage = (index) => {
  uploadedImages.value.splice(index, 1)
}

const uploadImages = async () => {
  const imageUrls = []

  for (let i = 0; i < uploadedImages.value.length; i++) {
    const tempFilePath = uploadedImages.value[i]

    // 使用uni.uploadFile上传图片
    const uploadResult = await new Promise((resolve) => {
      uni.uploadFile({
        url: '/uploadFile', // 替换为实际的上传接口地址
        filePath: tempFilePath,
        name: 'file',
        formData: {
          path: 'issueImages',
        },
        /* header: {
          // 如果需要认证token，可以在这里添加
          // 'Authorization': 'Bearer ' + token
        }, */
        success: (uploadRes) => {
          resolve(uploadRes)
        },
        fail: (error) => {
          resolve(null)
        }
      })
    })

    console.log('uploadResult',uploadResult)
    if (uploadResult && uploadResult.statusCode === 200) {
      // 假设返回的数据中包含图片URL
      const result = JSON.parse(uploadResult.data)
      console.log('上传成功result:', result)
      imageUrls.push(result.data) // 根据实际API返回结构调整
      console.log('上传成功imageUrls:', imageUrls)
    }
  }
  return imageUrls
}
// 提交报告
const submitReport = async () => {
  if (selectedIssueTypeIndex.value === -1) {
    uni.showToast({
      title: '请选择异常类型',
      icon: 'none'
    })
    return
  }

  if (!reportContent.value.trim()) {
    uni.showToast({
      title: '请填写详细描述',
      icon: 'none'
    })
    return
  }

  isSubmitting.value = true

  try {
    // 如果有图片需要上传，先上传图片
    let imageUrls =ref([]) 
    if (uploadedImages.value.length > 0) {
      imageUrls = await uploadImages()
      // 如果图片上传失败，可以给出提示或继续提交（根据业务需求）
    }

    // 构造提交数据
    const reportData = {
      treeId: treeInfo.value.treeId,
      issueType: selectedIssueTypeIndex.value,
      description: reportContent.value,
      contactInfo: contactInfo.value,
      photoUrls: imageUrls // 使用上传后的图片URL
    }

    // 提交表单数据

    console.log('提交数据:', reportData)
    const result = await postIssueTreeAPI(reportData)
    if (result.code == 1) {
      // 提交成功
      uni.showToast({
        title: '报告提交成功',
        icon: 'success'
      })
      // 返回上一页
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      // 提交失败
      uni.showToast({
        title: '提交失败，请重试',
        icon: 'none'
      })
    }

  } catch (error) {
    console.error('提交出错:', error)
    uni.showToast({
      title: '提交出错，请重试',
      icon: 'none'
    })
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style lang="scss">
.report-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.content {
  flex: 1;
  padding: 20rpx;
}

.form-container {
  .section {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

    .section-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #35c8a9;
      margin-bottom: 30rpx;
      padding-left: 10rpx;
      border-left: 6rpx solid #35c8a9;
    }

    .tree-info {
      padding: 20rpx;
      background-color: #f0f8f6;
      border-radius: 10rpx;

      .tree-name {
        display: block;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
      }

      .tree-location {
        font-size: 24rpx;
        color: #666;
      }
    }

    .form-item {
      margin-bottom: 30rpx;

      .label {
        display: block;
        font-size: 28rpx;
        color: #333;
        margin-bottom: 15rpx;
        font-weight: bold;
      }

      .picker {
        padding: 20rpx;
        border: 1rpx solid #ddd;
        border-radius: 10rpx;
        background-color: #fff;
        color: #666;

        .placeholder {
          color: #999;
        }
      }

      .textarea {
        width: 100%;
        height: 200rpx;
        padding: 20rpx;
        border: 1rpx solid #ddd;
        border-radius: 10rpx;
        box-sizing: border-box;
        font-size: 28rpx;
        background-color: #fff;
      }

      .char-count {
        text-align: right;
        font-size: 24rpx;
        color: #999;
        margin-top: 10rpx;
      }

      .input {
        width: 100%;
        padding: 20rpx;
        border: 1rpx solid #ddd;
        border-radius: 10rpx;
        box-sizing: border-box;
        font-size: 28rpx;
        background-color: #fff;
        min-height: 80rpx;
        /* 增加最小高度确保显示完整 */
        line-height: 40rpx;
        /* 设置行高以确保文字垂直居中 */
      }
    }

    .image-upload-section {
      .image-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 20rpx;
        margin-bottom: 20rpx;
      }

      .image-item {
        position: relative;
        aspect-ratio: 1/1;

        .uploaded-image {
          width: 100%;
          height: 100%;
          border-radius: 10rpx;
        }

        .remove-btn {
          position: absolute;
          top: -15rpx;
          right: -15rpx;
          width: 40rpx;
          height: 40rpx;
          border-radius: 50%;
          background-color: #ff6b6b;
          color: white;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 30rpx;
        }
      }

      .upload-btn {
        aspect-ratio: 1/1;
        border: 2rpx dashed #ddd;
        border-radius: 10rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: #999;

        .upload-icon {
          font-size: 60rpx;
          line-height: 1;
        }

        .upload-text {
          font-size: 24rpx;
          margin-top: 10rpx;
        }
      }

      .upload-hint {
        font-size: 24rpx;
        color: #999;
        text-align: center;
      }
    }
  }
}

.footer {
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);

  .submit-btn {
    width: 100%;
    padding: 25rpx 0;
    border: none;
    border-radius: 50rpx;
    font-size: 32rpx;
    font-weight: bold;
    background: linear-gradient(45deg, #35c8a9, #2a9d8f);
    color: white;

    &:disabled {
      background: #ccc;
    }
  }
}
</style>